import { Notify } from "quasar";
import { ref } from "vue";
import { v4 as uuidv4 } from "uuid";
import { useAPIStore } from "stores/api";

export const isConnected = ref(false); // 连接状态
export const status = ref({}); //  amr状态

let ws = null;

/**
 * 创建ws连接
 */
export default function createWs() {
  const clientID = ref(uuidv4());
  ws = new WebSocket(useAPIStore().wsUrl + clientID.value);
  if (ws) {
    ws.onmessage = (e) => {
      wsOnMessage(e);
    };
    ws.onopen = () => {
      isConnected.value = true;
      heartCheck.start();
    };
    ws.onclose = () => {
      isConnected.value = false;
    };
    ws.onerror = () => {
      isConnected.value = false;
      reConnect();
    };
  } else {
    reConnect();
  }
}

/**
 * 设置心跳
 */
const heartCheck = {
  timeoutObj: null,
  start: () => {
    heartCheck.timeoutObj = setTimeout(function () {
      if (isConnected.value) ws.send("heartbeat");
      else reConnect();
    }, 1000);
  },
  reset: () => {
    clearTimeout(heartCheck.timeoutObj);
    heartCheck.start();
  },
};

let rec;

/**
 * 重连机制
 */
function reConnect() {
  console.log("尝试重连");
  if (isConnected.value) return;
  rec && clearTimeout(rec);
  rec = setTimeout(createWs, 5000);
}

/**
 * ws接收消息
 */
function wsOnMessage(e) {
  heartCheck.reset();
  // 接收服务器返回的数据
  if (e.data !== "heartbeat") {
    const resData = JSON.parse(e.data);
    switch (resData.type.valueOf()) {
      case "notify":
        Notify.create({
          message: resData.content.message,
          type: resData.content.type,
        });
        break;
      case "status":
        status.value = resData.content;
        break;
    }
  }
}

/**
 * ws发送消息
 * @param type  协议类型（一般是一个单词）
 * @param data  协议内容
 */
export function sendCommand(type, data) {
  ws.send(
    JSON.stringify({
      type,
      content: data,
    })
  );
}

/**
 * 断开ws
 */
export function closeWs() {
  ws.close();
  clearTimeout(heartCheck.timeoutObj);
}
